package com.cowcode.controller;

import com.cowcode.biz.QuestionBiz;
import com.cowcode.biz.StudyBiz;
import com.cowcode.biz.TextBiz;
import com.cowcode.entity.Question;
import com.cowcode.entity.Text;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Controller
@RequestMapping("/excel")
public class ExcelController {

    @Resource
    private QuestionBiz questionBiz;
    @Resource
    private TextBiz textBiz;
    @Resource
    private StudyBiz studyBiz;

    @RequestMapping("/java")
    public void excel_home(HttpServletResponse response )throws IOException {
        studyBiz.updateDownload(1);
        response.setCharacterEncoding("UTF-8");
        List<Question> qlist=questionBiz.queryAll();
        List<Text> tlist = textBiz.queryAnswer();
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet页
        HSSFSheet sheet = wb.createSheet("问题信息");
        //创建标题行
        HSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("编号");
        titleRow.createCell(1).setCellValue("问题内容");
        titleRow.createCell(2).setCellValue("发布者");
        titleRow.createCell(3).setCellValue("语言");
        titleRow.createCell(4).setCellValue("时间");
        titleRow.createCell(5).setCellValue("回答");

        for(Question q:qlist){
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(q.getQid());
            dataRow.createCell(1).setCellValue(q.getQtext());
            dataRow.createCell(2).setCellValue(q.getUid().getUname());
            dataRow.createCell(3).setCellValue(q.getSid().getSname());
            dataRow.createCell(4).setCellValue(q.getQsend());
            int count = 5;
            for (Text text : tlist) {
                if (text.getQid()==q.getQid()){
                    dataRow.createCell(count).setCellValue(text.getTtext());
                    count++;
                }
            }

        }

        // 设置下载时客户端Excel的名称
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                + new String("问题与答案表".getBytes(),"iso-8859-1") + ".xls");

        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }


}
